/*
 * @description: request
 * @author: Jack Chen
 * @Date: 2022-04-24 10:01:40
 * @LastEditors: chenbinfa
 * @LastEditTime: 2023-01-18 10:15:02
 */

import _ from "lodash";
import store from "./store";

const cache = {};
const cacheEx = 1000;//cache time ms
const useStore = true;

const baseUrl = window.apiURL || "https://scan-api.cess.network";
const request = {
	/**
	 * get请求
	 * @param url
	 * @param options
	 * @returns {Promise<void>}
	 */
	get: (url, options = { method: "get", mode: "cors", headers: { "Content-Type": "application/json" } }) => {
		// console.log(url);
		return new Promise(async (resolve, reject) => {
			let tmp = cache[url];
			if (tmp) {
				if (tmp.status == 'ok') {
					return resolve(JSON.parse(tmp.res));
				} else {
					tmp.arr.push(resolve);
				}
				return;
			}
			cache[url] = { status: 'pending', arr: [resolve] };
			let res = await request.get2(url, options);
			if (window.apiStateCb) {
				window.apiStateCb(res.msg == 'API or network error');
			}
			if (useStore) {
				if (res.msg != 'ok') {
					let tmp = store.get(url);
					if (tmp && tmp.msg == 'ok') {
						res = tmp;
					}
				} else {
					store.set(url, res);
				}
			}
			res = JSON.stringify(res);
			let o = cache[url];
			if (o) {
				o.res = res;
				o.arr.forEach(t => {
					t(JSON.parse(res));
				});
				o.arr = [];
				o.status = 'ok';
				setTimeout(function () {
					delete cache[url];
				}, cacheEx);
			}
		});
	},
	get2: async (url, options = { method: "get", mode: "cors", headers: { "Content-Type": "application/json" } }) => {
		options = _.assign({ method: "get", mode: "cors", headers: { "Content-Type": "application/json" } }, options);
		// url = url + "?" + qs.stringify(options.data, { encodeValuesOnly: true }) + "&" + new Date().getTime();
		if (localStorage.getItem("token")) {
			options.headers["token"] = localStorage.getItem("token");
		}
		return ajax(url, options);
	},
	/**
	 * post请求
	 * @param url
	 * @param options
	 * @returns {Promise<void>}
	 */
	post: async (url, options = { method: "post" }) => {
		options.method = "post";
		if (!options.headers) {
			options.headers = { "Content-Type": "application/json" };
		}
		if (options.headers["Content-Type"] === "multipart/form-data") {
			options.body = options.data;
		} else {
			options.headers["Content-Type"] = "application/json";
			options.body = JSON.stringify(options.data);
		}
		if (localStorage.getItem("token")) {
			options.headers["token"] = localStorage.getItem("token");
		}
		// console.log("options", options);
		return ajax(url, options);
	}
};

async function ajax(url, options = {}) {
	if (url.indexOf("http") == -1) {
		url = baseUrl + url;
	}
	if (!options.method) options.method = "get";
	try {
		let response = await fetch(url, options);
		if (response.status >= 200 && response.status < 300) {
			return await response.json();
		} else {
			let ret = await response.json();
			ret.data = { content: [] };
			return ret;
		}
	} catch (e) {
		console.log(e);
		return { msg: 'API or network error' };
	}
	// return new Promise((resolve, reject) => {
	// 	fetch(url, options)
	// 		.then(res => {
	// 			return res.json();
	// 		})
	// 		.then(data => {
	// 			resolve(data);
	// 		})
	// 		.catch(error => {
	// 			console.log(error);
	// 			reject(error);
	// 		});
	// });
}
export default request;
